import asyncio
from PIL import Image, ImageDraw, ImageFont
import io
import random
import string

from fastapi import APIRouter
from fastapi.responses import (ORJSONResponse, HTMLResponse,Response,PlainTextResponse,UJSONResponse,
                               RedirectResponse,StreamingResponse,FileResponse)

router = APIRouter()

@router.get("/items", response_class=ORJSONResponse)
async def read_item():
    return ORJSONResponse([{"item_id":1,"name":"item1"},{"item_id":2,"name":"item2"}])

@router.get("/items2", response_class=HTMLResponse)
async def read_item2():
    return HTMLResponse("<html><body><h1>Hello World</h1></body></html>")

@router.get("/items3")
async def read_item3():
    html_content = """
    <html><body><h1>Hello World</h1></body></html>
    """
    return HTMLResponse(content=html_content, status_code=200)


@router.get("/response")
async def get_xml():
    xml_content = """<?xml version="1.0"?>
    <xml>
        <item>
            <id>1</id>
            <name>item1</name>
        </item>
        <item>
            <id>2</id>
            <name>item2</name>
        </item>
    </xml>
    """
    return Response(content=xml_content, media_type="application/xml")

@router.get("/plain_text")
async def get_text():
    return PlainTextResponse(content="Hello, World")

@router.get("/ujson")
async def get_ujson():
    return UJSONResponse(content={"message": "Hello, World"})

@router.get("/redirect")
async def redirect_to_baidu():
    return RedirectResponse(url="https://www.baidu.com")


async def video_streamer():
    for i in range(10):
        yield b"some video bytes: " + str(i).encode(encoding="utf-8") + b"\n"
        await asyncio.sleep(0.5)

@router.get("/streaming")
async def streaming_response_example():
    # """
    # 使用 StreamingResponse 可以返回一个可迭代对象，并支持分块传输。
    # """
    # async def get_content():
    #     for i in range(10):
    #         yield f"data: {i}\n\n"
    #         await asyncio.sleep(1)

    return StreamingResponse(video_streamer(),media_type="text/event-stream")

# 因为当前我的工作目录是上一级目录，所以要以工作目录开始再向上一级找到statics下的文件
file_path = "../statics/sp1.mp4"
@router.get("/video")
async def video_streamer():
    def iterfile():
        with open(file_path, "rb") as f:
            yield from  f

    return StreamingResponse(iterfile(),media_type="video/mp4")


# 生成一个验证码图片
def generate_captcha_image():
    # 创建图片和绘图对象
    image = Image.new('RGB', (120, 40), color=(255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 生成随机字符串
    text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))

    # 绘制文字（需提供字体路径或使用默认字体）
    try:
        font = ImageFont.truetype("arial.ttf", 30)
    except:
        font = ImageFont.load_default()

    draw.text((10, 5), text, fill=(0, 0, 0), font=font)

    # 添加干扰线等（可选）
    for _ in range(5):
        x1, y1 = random.randint(0, 120), random.randint(0, 40)
        x2, y2 = random.randint(0, 120), random.randint(0, 40)
        draw.line([(x1, y1), (x2, y2)], fill=(0, 0, 0), width=1)

    # 将图片保存到字节流
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    return img_byte_arr.getvalue()


@router.get("/captcha")
async def generate_captcha():
    # 假设你有一个生成验证码图片的函数，返回 bytes
    image_bytes = generate_captcha_image()  # 你需要实现这个函数
    # 使用io.BytesIO(image_bytes)把生成的验证码图片字节数据包装为一个二进制流对象
    return StreamingResponse(io.BytesIO(image_bytes), media_type="image/png")


def download_file_bytes():
    with open("../statics/image.png", "rb") as f:
        yield from f

@router.get("/downLoad")
async def download_file():
    # 假设你需要下载一个文件，返回 bytes
    file_bytes = download_file_bytes()  # 你需要实现这个函数
    # 添加这个自头来来指定下载的文件名称
    headers = {"Content-Disposition": "attachment; filename=my_image.png"}
    # 使用io.BytesIO(file_bytes)把下载的文件字节数据包装为一个二进制流对象
    return StreamingResponse(download_file_bytes(), media_type="application/octet-stream", headers=headers)

@router.get("/file")
async def get_file():
    return FileResponse(path="../statics/image.png", filename="new_imgae.png", media_type="application/octet-stream")